package service.impl;

import dao.DeptDao;
import model.Dept;
import service.DeptService;

import java.util.*;

public class DeptServiceImpl implements DeptService {

    private DeptDao deptDao = new DeptDao(Dept.class);
    @Override
    public List<Map<String, Object>> findAll() {
        List<Map<String, Object>> results = new ArrayList<>();
        Map<String, Object> deptMap;

        Set<String> deptIds = new HashSet<>();

        List<Map<String, Object>> all = deptDao.findDept();

        for(Map<String,Object> map : all){
            deptMap = new HashMap<>();
            String deptId = map.get("deptId").toString();
            String deptName = map.get("deptName").toString();
            if(!deptIds.contains(deptId)){
                deptMap.put("deptId",deptId);
                deptMap.put("deptName",deptName);
                results.add(deptMap);
                deptIds.add(deptId);
            }
        }

        for(Map<String,Object> dept : results){
            List<Map<String, Object>> userList = new ArrayList<>();
            String deptId = dept.get("deptId").toString();
            for(Map<String,Object> map : all){
                String deptId2 = map.get("deptId").toString();
                if(deptId.equals(deptId2)){
                   if(map.get("uId") != null){
                       userList.add(map);
                   }
                }
            }
            dept.put("userList",userList);
            dept.put("count",userList.size());
        }

        return results;
    }

    @Override
    public List<Map<String, Object>> findUserByDeptId(Integer deptId) {
        return deptDao.findUserByDeptId(deptId);
    }

}
